/**
 * 解析解密templet zip包
 */

const Promise = require('bluebird');
const zip = require('jszip');
const https = require('https');
const aes = require('../lib/aes');
const parser = require('./parse-json-safe');

const TEMPLET_ENC_KEY = process.env.TEMPLET_ENC_KEY;

module.exports = function(url) {
    const data = [];
    return Promise.try(() => {
        // https读取
        return new Promise((resolve, reject) => {
            https.get(url, function(res) {
                res.on('data', (chunk) => {
                    data.push(chunk);
                });
                res.on('end', resolve);
                res.on('err', reject);
            });
        });
    })
    .then(() => {
        // 加载zip包
        const buf = Buffer.concat(data);
        return zip.loadAsync(buf);
    })
    .then(zip => {
        return zip.file('config.json').async('nodebuffer');
    })
    .then(buf => {
        if(!buf) {
            return null;
        }
        // 解密
        const config = aes.decryption(buf, TEMPLET_ENC_KEY);
        return config.toString();
    })
    .then(config => {
        return parser(config);
    });
};
